<template>
  <div class="app-edit">
    <div class="edit-container">
      <!-- 页面头部 -->
      <div class="edit-header">
        <div class="header-left">
          <el-button @click="goBack" icon="ArrowLeft" circle />
          <h2>编辑应用</h2>
        </div>
        <div class="header-right">
          <el-button @click="goToChat" type="primary" icon="ChatDotRound">
            进入对话
          </el-button>
        </div>
      </div>

      <!-- 编辑表单 -->
      <div class="edit-content">
        <el-card class="form-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-tag v-if="appInfo.id" type="info" size="small">
                ID: {{ appInfo.id }}
              </el-tag>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120px"
            class="edit-form"
          >
            <el-form-item label="应用名称" prop="appName">
              <el-input
                v-model="form.appName"
                placeholder="请输入应用名称"
                maxlength="50"
                show-word-limit
                clearable
              />
              <div class="form-tip">
                给你的应用起一个有意义的名称，方便识别和管理
              </div>
            </el-form-item>

            <el-form-item label="应用描述" prop="initPrompt">
              <el-input
                v-model="form.initPrompt"
                type="textarea"
                :rows="4"
                placeholder="描述应用的功能和用途..."
                maxlength="500"
                show-word-limit
                readonly
              />
              <div class="form-tip">
                应用的初始提示词，创建后不可修改
              </div>
            </el-form-item>

            <el-form-item label="创建时间">
              <el-input
                :value="formatTime(appInfo.createTime)"
                readonly
              />
            </el-form-item>

            <el-form-item label="最后更新">
              <el-input
                :value="formatTime(appInfo.updateTime)"
                readonly
              />
            </el-form-item>

            <el-form-item v-if="appInfo.deployKey" label="部署状态">
              <el-tag type="success" size="large">
                <el-icon><Check /></el-icon>
                已部署
              </el-tag>
              <div class="form-tip">
                部署标识: {{ appInfo.deployKey }}
              </div>
            </el-form-item>

            <el-form-item v-else label="部署状态">
              <el-tag type="info" size="large">
                <el-icon><Clock /></el-icon>
                未部署
              </el-tag>
            </el-form-item>

            <el-form-item>
              <div class="form-actions">
                <el-button 
                  type="primary" 
                  @click="saveApp" 
                  :loading="saving"
                  size="large"
                >
                  保存修改
                </el-button>
                <el-button 
                  @click="resetForm" 
                  size="large"
                >
                  重置
                </el-button>
                <el-button 
                  type="danger" 
                  @click="deleteApp" 
                  :loading="deleting"
                  size="large"
                  plain
                >
                  删除应用
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 应用预览卡片 -->
        <el-card class="preview-card" shadow="never" v-if="appInfo.id">
          <template #header>
            <span>应用预览</span>
          </template>
          
          <div class="app-preview">
            <div class="preview-cover">
              <img v-if="appInfo.cover" :src="appInfo.cover" :alt="appInfo.appName" />
              <div v-else class="default-preview-cover">
                <el-icon size="60"><Document /></el-icon>
              </div>
            </div>
            
            <div class="preview-info">
              <h3>{{ form.appName || '未命名应用' }}</h3>
              <p class="preview-desc">{{ form.initPrompt || '暂无描述' }}</p>
              
              <div class="preview-stats">
                <div class="stat-item">
                  <span class="stat-label">创建时间</span>
                  <span class="stat-value">{{ formatDate(appInfo.createTime) }}</span>
                </div>
                <div class="stat-item" v-if="appInfo.deployedTime">
                  <span class="stat-label">部署时间</span>
                  <span class="stat-value">{{ formatDate(appInfo.deployedTime) }}</span>
                </div>
              </div>
              
              <div class="preview-actions">
                <el-button type="primary" @click="goToChat" icon="ChatDotRound">
                  开始对话
                </el-button>
                <el-button 
                  v-if="previewUrl" 
                  @click="openPreview" 
                  icon="View"
                  type="success"
                  plain
                >
                  预览效果
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup name="AiAppEdit">
import { ref, reactive, onMounted, getCurrentInstance, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, ChatDotRound, Check, Clock, Document, View } from '@element-plus/icons-vue'
import { getAppDetail, updateUserApp, deleteUserApp } from '@/api/ai/app'
import { parseTime } from '@/utils/ruoyi'

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()

// 响应式数据
const appInfo = ref({})
const saving = ref(false)
const deleting = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null,
  appName: '',
  initPrompt: ''
})

// 表单验证规则
const rules = {
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 1, max: 50, message: '应用名称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 计算预览URL
const previewUrl = computed(() => {
  if(appInfo.value.codeGenType && appInfo.value.id && appInfo.value.codeGenType === 'vue_project'){
    return `/preview-api/static/${appInfo.value.codeGenType}_${appInfo.value.id}/dist/index.html`
  }else{
    return `/preview-api/static/${appInfo.value.codeGenType}_${appInfo.value.id}/`
  }
  return ''
})

// 获取应用详情
const loadAppInfo = async () => {
  try {
    const response = await getAppDetail(route.params.appId)
    if (response.code === 200) {
      appInfo.value = response.data
      // 填充表单
      form.id = response.data.id
      form.appName = response.data.appName || ''
      form.initPrompt = response.data.initPrompt || ''
    } else {
      proxy.$modal.msgError('获取应用详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取应用详情失败:', error)
    proxy.$modal.msgError('获取应用详情失败')
    goBack()
  }
}

// 保存应用
const saveApp = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    saving.value = true
    const response = await updateUserApp({
      id: form.id,
      appName: form.appName
    })
    
    if (response.code === 200) {
      proxy.$modal.msgSuccess('保存成功')
      // 更新本地数据
      appInfo.value.appName = form.appName
      appInfo.value.updateTime = new Date().toISOString()
    } else {
      proxy.$modal.msgError(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存应用失败:', error)
    proxy.$modal.msgError('保存失败')
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 重新填充原始数据
  form.appName = appInfo.value.appName || ''
  form.initPrompt = appInfo.value.initPrompt || ''
}

// 删除应用
const deleteApp = async () => {
  try {
    await proxy.$modal.confirm(
      `确定要删除应用"${form.appName || '未命名应用'}"吗？\n删除后将无法恢复！`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    deleting.value = true
    const response = await deleteUserApp({ id: form.id })
    
    if (response.code === 200) {
      proxy.$modal.msgSuccess('删除成功')
      // 跳转回首页
      router.push('/ai/home')
    } else {
      proxy.$modal.msgError(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除应用失败:', error)
      proxy.$modal.msgError('删除失败')
    }
  } finally {
    deleting.value = false
  }
}

// 跳转到对话页面
const goToChat = () => {
  router.push(`/ai/chat/${route.params.appId}`)
}

// 打开预览
const openPreview = () => {
  if (previewUrl.value) {
    window.open(previewUrl.value, '_blank')
  }
}

// 返回
const goBack = () => {
  router.push('/ai/home')
}

// 格式化时间
const formatTime = (time) => {
  return time ? parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}') : '暂无'
}

// 格式化日期
const formatDate = (time) => {
  return time ? parseTime(time, '{y}-{m}-{d}') : '暂无'
}

// 页面加载时获取应用信息
onMounted(() => {
  loadAppInfo()
})
</script>

<style scoped>
.app-edit {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.edit-container {
  max-width: 1200px;
  margin: 0 auto;
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 5px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
  font-weight: 600;
}

.edit-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.form-card {
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-form {
  padding: 20px 0;
}

.form-tip {
  font-size: 0.8rem;
  color: #999;
  margin-top: 5px;
  line-height: 1.4;
}

.form-actions {
  display: flex;
  gap: 15px;
  padding-top: 20px;
  border-top: 1px solid #e1e8ed;
}

.preview-card {
  border-radius: 12px;
  height: fit-content;
}

.app-preview {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.preview-cover {
  width: 100%;
  height: 150px;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-preview-cover {
  color: #999;
}

.preview-info h3 {
  margin: 0 0 10px 0;
  font-size: 1.2rem;
  color: #333;
  font-weight: 600;
}

.preview-desc {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.5;
  margin: 0 0 15px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.preview-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.9rem;
}

.stat-label {
  color: #666;
}

.stat-value {
  color: #333;
  font-weight: 500;
}

.preview-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.preview-actions .el-button {
  width: 100%;
}

@media (max-width: 768px) {
  .app-edit {
    padding: 15px;
  }
  
  .edit-header {
    margin-bottom: 15px;
  }
  
  .header-left {
    gap: 10px;
  }
  
  .header-left h2 {
    font-size: 1.3rem;
  }
  
  .edit-content {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
  
  .edit-form {
    padding: 15px 0;
  }
}

@media (max-width: 480px) {
  .edit-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-right {
    display: flex;
    justify-content: center;
  }
}

/* Element Plus 样式覆盖 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #333;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  border-radius: 8px;
}

:deep(.el-card__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #e1e8ed;
}

:deep(.el-card__body) {
  padding: 24px;
}
</style>
